package com.lzg.extend

import com.google.gson.JsonSyntaxException
import com.lzy.okgo.OkGo
import com.lzy.okgo.exception.HttpException
import com.lzy.okgo.exception.StorageException
import com.lzy.okrx2.adapter.ObservableBody
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import org.json.JSONException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

fun <T> post(url: String, vararg pairs: Pair<String, String?>): Observable<BaseResponse<T>> {
    return OkGo.post<BaseResponse<T>>(url)
        .params(mapOf(*pairs))
        .converter(object : JsonConvert<BaseResponse<T>>() {})
        .adapt(ObservableBody<BaseResponse<T>>())
}

fun <T> get(url: String, vararg pairs: Pair<String, String?>): Observable<BaseResponse<T>> {
    return OkGo.get<BaseResponse<T>>(url)
        .params(mapOf(*pairs))
        .converter(object : JsonConvert<BaseResponse<T>>() {})
        .adapt(ObservableBody<BaseResponse<T>>())
}

fun Disposable.toDisposables(disposables: CompositeDisposable) {
    disposables.add(this)
}

fun onFailed(exception: Throwable): String {
    return if (exception is IllegalStateException) {
        exception.message?:"IllegalStateException"
    } else if (exception is UnknownHostException || exception is ConnectException) {
        "网络连接失败，请连接网络！"
    } else if (exception is SocketTimeoutException) {
        "网络请求超时！"
    } else if (exception is HttpException) {
        "服务器发生未知错误！"
    } else if (exception is StorageException) {
        "SD卡不存在或没有权限！"
    } else if (exception is JsonSyntaxException || exception is JSONException) {
        "数据格式错误或解析失败！"
    } else {
        "网络数据请求失败！"
    }
}